Running Docker Container as a Non Root User

Docker Containers run as Root Users by default. On running the applications inside Docker Containers, you can access all the root privileges. This poses a security threat when you deploy applications on large scale inside Docker Containers. If your application gets hacked by external users, other applications running inside the Containers would also be at risk. If your Docker Container is part of a network, then the whole network is at risk. To avoid this, you need to make sure that you run the Docker Containers as non-root users.

Following are the two different ways to create and add non-root users inside Docker Containers.

  1. Adding a User to the Docker Group

    1. Run Docker Containers as a Non Root User by adding Users to the Docker Group. If there is no Docker group, create a Docker Group using the following command:

      sudo groupadd docker

    2. If there is already a Docker group in your local machine, the output of the below command would be –

      groupadd: group 'docker' already exists

    3. After you have created the Docker Group, you can now add Non Root Users using the following command:

      sudo usermod −aG docker [non−root user]

    4. Re−login to your Docker, to verify the group membership.

  2. Using Dockerfile

    Another simpler solution to access a Docker Container using Non Root User, is to specify the instructions in the Dockerfile using the following instructions:

    1. Add the USER in docket using the −u flag along with the useradd command and then using the USER instruction.

    2. Pull the base image as Ubuntu

      FROM ubuntu:latest

    3. #Add a user with userid 8877 and name nonroot

    4. RUN useradd −u 8877 nonroot

    5. #Run Container as nonroot

      USER nonroot

    6. In kubernetes, this can be configured in Security Context using runAsNonRoot field e.g.:

      Copy
      kind: ... 
      apiVersion: ... 
      metadata: 
        name: ... 
      spec: 
      ...
        containers: 
        - name: ... 
          image: .... 
          securityContext: 
      ...
                runAsNonRoot: true 
      ...
    7. Configure as a Kubernetes cluster administrator using Pod Security Policies.